package com.company.project.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.exception.BusinessException;
import com.company.project.common.utils.Constant;
import com.company.project.common.utils.DateUtils;
import com.company.project.common.utils.SyncDataResult;
import com.company.project.entity.MatchProjectEntity;
import com.company.project.entity.MatchTeamEntity;
import com.company.project.entity.SysUser;
import com.company.project.entity.TeamUserEntity;
import com.company.project.service.MatchProjectService;
import com.company.project.service.MatchTeamService;
import com.company.project.service.TeamUserService;
import com.company.project.service.UserService;
import com.company.project.vo.req.SyncTeamParam;
import com.company.project.vo.req.SyncUserParam;
import com.company.project.vo.resp.SyncTeamResp;
import com.company.project.vo.resp.SyncUserResp;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RequestMapping("/open/api/sync")
@RestController
@Api(tags = "数据被动同步")
public class SyncDataController {

	@Resource
    private UserService userService;
	
	@Resource
	private MatchTeamService matchTeamService;
	
	@Resource
	private MatchProjectService matchProjectService;
	
	@Resource
	private TeamUserService teamUserService;
	
	@PostMapping("/user")
    @ApiOperation(value = "用户数据同步接口")
	public SyncDataResult syncUser(@RequestBody @Valid SyncUserParam dto) {
		
		List<SyncUserResp> result = new ArrayList<>();			
		LambdaQueryWrapper<TeamUserEntity> queryWrapper = Wrappers.lambdaQuery();				
		if(!StringUtils.isEmpty(dto.getDcic_user_id())) {
			SysUser user = userService.getUserByDcicUserId(dto.getDcic_user_id());
			if (user == null) {
	            throw new BusinessException("用户不存在！");
	        }
			queryWrapper.eq(TeamUserEntity::getDcicUserId, dto.getDcic_user_id());
		}	
		List<TeamUserEntity> teamUsers = teamUserService
				.list(queryWrapper);
		for(TeamUserEntity teamUser:teamUsers) {
			
			String dcic_user_id = teamUser.getDcicUserId();
			String team_id = "d18xm8uuiwe5315l-10004-"+teamUser.getTeamId();
			String track_user_name = teamUser.getName();
			LambdaQueryWrapper<MatchTeamEntity> mtqueryWrapper = Wrappers.lambdaQuery();
			mtqueryWrapper.eq(MatchTeamEntity::getTeamId, teamUser.getTeamId());              		
	        MatchTeamEntity team = matchTeamService.getOne(mtqueryWrapper);
			String team_name = team.getTeamName();
			String attach = team.getTeamBrief();
			String sign_at = DateUtils.format(teamUser.getCreateTime(), DateUtils.DATE_TIME_PATTERN);
			
			//queryWrapper.clear();
			LambdaQueryWrapper<TeamUserEntity> queryLeaderWrapper = Wrappers.lambdaQuery();
			queryLeaderWrapper.eq(TeamUserEntity::getTeamId, teamUser.getTeamId()); 
			queryLeaderWrapper.eq(TeamUserEntity::getIsCaptain, Constant.IS_TRUE); 
			TeamUserEntity leader = teamUserService.getOne(queryLeaderWrapper);
			/*teamUser = teamUserService.getOne(queryWrapper);*/
			if (leader == null) {
			    throw new BusinessException("队伍"+team_name+"不存在队长！");
			}
			
			/*SysUser leader = userService.getUserByDcicUserId(teamUser.getDcicUserId());
			if (leader == null) {
			    throw new BusinessException("该队伍不存在队长！");
			}*/
			String team_leader_id = leader.getDcicUserId();
			String team_leader_name = leader.getName();
			SyncUserResp resp = new SyncUserResp(dcic_user_id, track_user_name, "10004", team_id, 
					team_name, team_leader_id, team_leader_name, attach, teamUser.getName(),
					teamUser.getIdNumber(), teamUser.getPhone(),  teamUser.getProvince(), 
					teamUser.getCity(), teamUser.getSchool(), teamUser.getDegree(),
					teamUser.getMajor(), teamUser.getOrganization(), teamUser.getPost(), sign_at, teamUser.getEmail(), teamUser.getRemark());
			result.add(resp);
		}				
		return SyncDataResult.success(result);	
	}
	
	@PostMapping("/rank")
    @ApiOperation(value = "队伍排名同步接口")
	public SyncDataResult syncTeam(@RequestBody @Valid SyncTeamParam dto) {
		List<SyncTeamResp> result = new ArrayList<>();	
		String dcic_match_id = dto.getDcic_match_id();
		if(StringUtils.isEmpty(dcic_match_id)||"10004".equals(dcic_match_id)) {
			LambdaQueryWrapper<MatchProjectEntity> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.isNotNull(MatchProjectEntity::getRank);
			queryWrapper.isNotNull(MatchProjectEntity::getVote);
	        //查询条件示例	                              	        
	        List<MatchProjectEntity> list = matchProjectService.list(queryWrapper);
	        // 仅仅同步有票数和排名的项目
			for (MatchProjectEntity entity : list) {

				if (entity.getRank() != null && entity.getVote() != null) {
					SyncTeamResp teamResp = new SyncTeamResp();
					teamResp.setDcic_match_id("10004");
					teamResp.setTeam_id("d18xm8uuiwe5315l-10004-" + entity.getTeamId());
					MatchTeamEntity team = matchTeamService.getOne(
							Wrappers.<MatchTeamEntity>lambdaQuery().eq(MatchTeamEntity::getTeamId, entity.getTeamId()));
					teamResp.setTeam_name(team.getTeamName());
					teamResp.setRank(entity.getRank());
					teamResp.setScore(entity.getVote().doubleValue());
					result.add(teamResp);
				}

			}
		}
		
		return SyncDataResult.success(result);
		
	}
	
}
